package com.bigwolf.gateway.filter;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bigwolf.common.core.utils.ServletUtils;
import com.bigwolf.gateway.service.ValidateCodeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicReference;

@Component
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object> {
    private final static String[] VALIDATE_URL = new String[] { "/auth/login", "/auth/register" };

    private static final String CODE = "code";

    private static final String UUID = "uuid";

    @Autowired
    private ValidateCodeService validateCodeService;
    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            if(!StringUtils.equalsAnyIgnoreCase(request.getURI().getPath(), VALIDATE_URL)) {
                return chain.filter(exchange);
            }
            try {
                String rspStr = resolveBodyFromRequest(request);
                JSONObject obj = JSON.parseObject(rspStr);
                //String rspStr = request.getPath().toString();
                System.out.println("url:" + obj.get(UUID) + ":" + obj.get(CODE));
                validateCodeService.checkCaptcha(obj.getString(CODE), obj.getString(UUID));
            } catch (Exception e) {
                System.out.println("验证码异常");
                return ServletUtils.webFluxResponseWriter(exchange.getResponse(), e.getMessage());
            }

            return chain.filter(exchange);
        };
    }

//    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest) {
//        Flux<DataBuffer> body = serverHttpRequest.getBody();
//        AtomicReference<String> bodyRef = new AtomicReference<>();
//        body.subscribe(dataBuffer -> {
//            ByteBuffer bb = dataBuffer.asByteBuffer();
//            CharBuffer cb = StandardCharsets.UTF_8.decode(bb);
//            DataBufferUtils.release(dataBuffer);
//            bodyRef.set(cb.toString());
//        });
//        return bodyRef.get();
//    }

    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest)
    {
        // 获取请求体
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        body.subscribe(buffer -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
            DataBufferUtils.release(buffer);
            bodyRef.set(charBuffer.toString());
        });
        return bodyRef.get();
    }
}
